<?php
//------------------------
// 购物车模型
//-------------------------
namespace app\common\model;

use think\Model;
use think\Db;
use think\Session;
use think\Cookie;

class Cart extends Model{

    // 添加到购物车
    public function addToCart($addData){

    	$user_id = Session::get('user_id');

    	if($user_id){
			$has = $this->where('user_id',$user_id)
				 ->where('goods_id',$addData['goods_id'])
				 ->where('goods_spec_key',$addData['goods_spec_key'])
				 ->find();

				 // halt($has);
			// 判断是否商品已经存在
			if($has){
				$this->where('id',$has['id'])->setInc('quantity', $addData['quantity']);
			} else {
				$addData['user_id'] = $user_id;
				$this->save($addData);
			}

		} else {
			// 先从COOKIE中取出购物车的数组
			$cart = Cookie::has('cart') ? unserialize(Cookie::get('cart')) : array();
			// 把商品加入到这个数组中
			$key = $addData['goods_id'] . ':' . $addData['goods_spec_key'];
			// 先判断数组中有没有这件商品
			if(isset($cart[$key])){
				$cart[$key] += $addData['quantity'];
			} else {
				$cart[$key] = $addData['quantity'];
			}

			// 把处理好的数组保存回COOKIE中
	    	$cart = serialize($cart);
	    	Cookie::set('cart', $cart, 30 * 86400);
		}

    }

    // 更新商品数量
    public function updateData($updateData){
    	$user_id = Session::get('user_id');

    	if($user_id){
    		$this->where('user_id',$user_id)
    			 ->where('goods_id',$updateData['goods_id'])
    			 ->where('goods_spec_key',$updateData['goods_spec_key'])
    			 ->update(array('quantity' => $updateData['quantity']) );
    	} else {
    		$cart = Cookie::has('cart') ? unserialize(Cookie::get('cart')) : array();
    		$key = $updateData['goods_id'] . ':' . $updateData['goods_spec_key'];

    		$cart[$key] = $updateData['quantity'];

    		$cart = serialize($cart);
	    	Cookie::set('cart', $cart, 30 * 86400);
    	}
    }

    // 从购物车中删除商品
    public function delToCart($cart_id,$goods_spec_key){
    	$user_id = Session::get('user_id');

    	if($user_id){

    		$res = $this->where('id',$cart_id)->delete();

    		if ($res) {
    			return true;
    		} else {
    			return false;
    		}

		} else {
			// 先从COOKIE中取出购物车的数组
			$cart = Cookie::has('cart') ? unserialize(Cookie::get('cart')) : array();

			// 先判断数组中有没有这件商品
			if(isset($cart[$goods_spec_key])){
				unset($cart[$goods_spec_key]);
			}

			// 把处理好的数组保存回COOKIE中
	    	$cart = serialize($cart);
	    	Cookie::set('cart', $cart, 30 * 86400);

	    	return true;
		}

    }

    // 清空购物车
    public function emptyCart(){
    	$user_id = Session::get('user_id');

    	if($user_id){
    		$res = $this->where('user_id',$user_id)->delete();
		} else {
			Cookie::delete('cart');
		}
    }

    // 获取购物车数据
    public function getCartInfo(){
    	$user_id = Session::get('user_id');
    	$cart = array();

    	if($user_id){
    		$cart = $this->where('user_id',$user_id)->select()->toArray();
    	} else {
    		$_cart = Cookie::has('cart') ? unserialize(Cookie::get('cart')) : array();

    		foreach ($_cart as $k => $v){
    			// 从下标中解析出商品ID和商品属性ID
    			$_k = explode(':', $k);
    			$cart[] = array(
    				'goods_id' => (int)$_k[0],
    				'goods_spec_key' => $_k[1],
    				'quantity' => (int)$v,
    				'user_id' => 0,
    				'id' => 0,
    			);
    		}
    	}

		foreach ($cart as $k => $v) {
			$goodsInfo = Db('Goods')->field('goods_image,goods_name')->where('id',$v['goods_id'])->find();
			$cart[$k]['goods_name'] = $goodsInfo['goods_name'];
			$cart[$k]['goods_image'] = $goodsInfo['goods_image'];

			// 先查出规格key值对应价格,规格key值为0时直接采用商品实时现价
			if ($v['goods_spec_key'] == 0) {
				$res = Db('Goods')->field('now_price')->where('id',$v['goods_id'])->find();
				$_price = $res['now_price'];
				$goodsSpecDetails = '';

			} else {
				$res = Db('GoodsSpec')->field('price,key_name')->where('goods_id',$v['goods_id'])->where('key',$v['goods_spec_key'])->find();
				$_price = $res['price'];
				$goodsSpecDetails = $res['key_name'];
			}
			// 再实时计算会员价格
			$cart[$k]['price'] = model('Goods')->calculationPrice($v['goods_id'],$_price);

			// 商品规格详情
			$cart[$k]['spec_details'] = str_replace(' ', "\n", $goodsSpecDetails);
		}

		return $cart;

    }

    // 把COOKIE中的数据转移到数据库中
	public function dataCookieToDb(){
		$user_id = Session::get('user_id');

		if($user_id){
			$cart = Cookie::has('cart') ? unserialize(Cookie::get('cart')) : array();
			if($cart){
				foreach ($cart as $k => $v){
					$_k = explode(':', $k);
					$addData = array(
							'goods_id' => $_k[0],
							'goods_spec_key' => $_k[1],
							'quantity' => $v
						);
					$this->addToCart($addData);
				}

				Cookie::delete('cart');
			}
		}
	}


	/**
     * remark    : 获取勾选了的购物车中的数据，并计算出小计与总价
     * author    : 李嘉华
     * @param $cart array
     * @param $buythis array
     * @return $res array
     */
	public function getCartToBuyThis($cart,$buythis){
		$res        = array();
		$info       = array();
		$totalPrice = 0;
		$i          = 0;
		foreach ($cart as $k => $v){
			// 判断这件商品有没有被选择
			if(!in_array($v['goods_id'].':'.$v['goods_spec_key'], $buythis)){
				continue;
			}
			// // 取出这件商品的库存量
			// $storeCount = Db('GoodsSpec')->where('goods_id',$v['goods_id'])->where('key',$v['goods_spec_key'])->field('store_count')->find();
			// if($storeCount['store_count'] < $v['quantity']){
			// 	return false;
			// }
			$info[$i]['id']             = $v['id'];
			$info[$i]['goods_id']       = $v['goods_id'];
			$info[$i]['user_id']        = $v['user_id'];
			$info[$i]['goods_spec_key'] = $v['goods_spec_key'];
			$info[$i]['quantity']       = $v['quantity'];
			$info[$i]['goods_name']     = $v['goods_name'];
			$info[$i]['goods_image']    = $v['goods_image'];
			$info[$i]['price']          = $v['price'];
			$info[$i]['spec_details']   = $v['spec_details'];
			$info[$i]['subtotal'] = $v['price'] * $v['quantity'];
			// 计算总价
			$totalPrice += $info[$i]['subtotal'];

			$i = ++$i;
		}

		$res['totalPrice'] = $totalPrice;
		$res['info']       = $info;

		return $res;

	}

	// 清掉购物车中已经下单的商品
	public function clearBuythis(){
		$user_id = Session::get('user_id');
		if($user_id) {
			// 取出勾选的商品
			$buythis = Session::get('buythis');
			// halt($busythis);
			$cartModel = Db('Cart');
			// 循环勾选 的商品进行删除
			foreach ($buythis as $k => $v){
				$_v = explode(':', $v);
				$cartModel
				->where('user_id',$user_id)
				->where('goods_id',$_v[0])
				->where('goods_spec_key',$_v[1])
				->delete();
			}

			//删除session中的buythis
			Session::delete('buythis');
		}
	}






}